#include "iodevice.h"

struct system_runpar_str system_runpar;
struct system_par_str system_par;
struct system_static_data_str *system_static_data;
/*******************************************************************
********************************************************************/
void device_out_set(int index, int stas)
{
    if (stas == 0)
    {
        Clr_Bit(system_runpar.channel_stas, (1 << index));
    }
    else
    {
        Set_Bit(system_runpar.channel_stas, (1 << index));
    }

    if (system_runpar.channel_stas != nvm_data[NVM_STAS].value)
    {
        nvm_data[NVM_STAS].value = system_runpar.channel_stas;
        nvm_save(&nvm_data[NVM_STAS]);
    }
    pilot_par.pilot_stas = stas;
    out_set(stas,index);
}
/*******************************************************************
********************************************************************/
void work_timer_check(void)
{
    static uint32_t work_time = 0;
    static uint32_t run_time = 0;
    run_time++;
    if (system_runpar.channel_stas)
        work_time++;

    if (work_time >= 36000)
    {
        work_time = 0;
        nvm_data[NVM_WORKT].value++;
        nvm_save(&nvm_data[NVM_WORKT]);
    }

    if (run_time >= 36000)
    {
        run_time = 0;
        nvm_data[NVM_RUNT].value++;
        nvm_save(&nvm_data[NVM_RUNT]);
    }
}

/*******************************************************************
 * 100ms
********************************************************************/
void gpio_dev_tick(void *ARG)
{
    blink_check();
    work_timer_check();
    system_runpar.timer++;
    if (system_runpar.timer == 30)
    {
        Serial.printf("NVM_LDNUM:%d\n", nvm_data[NVM_LDNUM].value);
        if (nvm_data[NVM_LDNUM].value >= 5) //连续重启5次复位
        {
            nvm_data[NVM_LDNUM].value = 0;
            nvm_save(&nvm_data[NVM_LDNUM]);
            void settingsClear();
            settingsClear();
        }
        else
        {
            nvm_data[NVM_LDNUM].value = 0;
            nvm_save(&nvm_data[NVM_LDNUM]);
        }
    }
    RTC_Clock_hdl();
}

/*******************************************************************
********************************************************************/
void system_reload(void)
{
    //board_par_reload();
}

/*******************************************************************
********************************************************************/
void gpio_dev_init(void)
{
    blink_start(6, 5, 5);

    system_param_load();
    nvm_datainit();

    nvm_data[NVM_LDNUM].value++;

    nvm_save(&nvm_data[NVM_LDNUM]);

    device_out_set(0, nvm_data[NVM_STAS].value);
}
